package com.lyc.campuslife.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.lyc.campuslife.dto.Result;
import com.lyc.campuslife.entity.VoucherOrder;
import com.lyc.campuslife.mapper.VoucherOrderMapper;
import com.lyc.campuslife.service.ISeckillVoucherService;
import com.lyc.campuslife.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lyc.campuslife.utils.RedisIdWorker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lyc
 * @since 2024-05-07
 */
@Slf4j
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {
    @Resource
    private IVoucherOrderService voucherOrderService;
    @Resource
    private ISeckillVoucherService seckillVoucherService;
    @Resource
    private RedisIdWorker redisIdWorker;//用于生成订单号
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    //脚本对象生成
    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    static {
        SECKILL_SCRIPT  = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("luaScript/seckillVoucherOrder.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }
    //一人一单秒杀 reids端做下单判断 将订单发送到消息队列

    /**这是秒杀代金券的方法。它首先获取当前用户ID，然后调用 redisIdWorker.nextId 生成订单号。
    接着，执行Lua脚本 SECKILL_SCRIPT 来检查库存并尝试扣减库存。
    Lua脚本的结果决定了用户是否具有购买资格。如果没有购买资格，返回失败的 Result 对象；如果有，返回包含订单号的成功 Result 对象
    */
    @Override
    public Result seckillVoucher(Long voucherId, Long userId) {
        long orderId = redisIdWorker.nextId("seckillVoucherOrder");
        // 1.执行lua脚本
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString(),String.valueOf(orderId)
        );
        int r = result.intValue();
        // 2.判断结果是否为0
        if (r != 0) {
            // 2.1.不为0 ，代表没有购买资格
            return Result.fail(r == 1 ? "库存不足" : "不能重复下单");
        }
        // 3.返回订单id
        return Result.ok(orderId);
    }

    //异步处理订单，从消息队列获取订单，并写入数据库
//    private IVoucherOrderService proxy;
    //静态线程池
    private static  final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();
    //项目启动，bean实例生成后就开始处理消息队列中的订单
    @PostConstruct
    private void init(){
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }
    private class VoucherOrderHandler implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    // 1.获取消息队列中的订单信息 XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS s1 >
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create("stream:orders", ReadOffset.lastConsumed())
                    );
                    // 2.判断订单信息是否为空
                    if (list == null || list.isEmpty()) {
                        // 如果为null，说明没有消息，继续下一次循环
                        continue;
                    }
                    // 解析数据
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> value = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    // 3.创建订单
                    boolean suc = voucherOrderService.createVoucherOrder(voucherOrder);
                    // 4.确认消息 XACK
                    if (suc)
                    stringRedisTemplate.opsForStream().acknowledge("stream:orders", "g1", record.getId());
                } catch (Exception e) {
                    log.error("处理订单异常", e);
                    //处理异常消息
                    handlePendingList();
                }
            }
        }
        private void handlePendingList() {
            while (true) {
                try {
                    // 1.获取pending-list中的订单信息 XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS s1 0
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1),
                            StreamOffset.create("stream:orders", ReadOffset.from("0"))
                    );
                    // 2.判断订单信息是否为空
                    if (list == null || list.isEmpty()) {
                        // 如果为null，说明没有异常消息，结束循环
                        break;
                    }
                    // 解析数据
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> value = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    // 3.创建订单
                    boolean suc = voucherOrderService.createVoucherOrder(voucherOrder);
                    // 4.确认消息 XACK
                    if (suc)
                    stringRedisTemplate.opsForStream().acknowledge("stream:orders", "g1", record.getId());
                } catch (Exception e) {
                    log.error("处理pendding订单异常", e);
                    try{
                        Thread.sleep(20);
                    }catch(Exception er){
                        er.printStackTrace();
                    }
                }
            }
        }


    }
    @Override
    @Transactional
    public boolean createVoucherOrder(VoucherOrder voucherOrder) {
        seckillVoucherService.update()
                .setSql("stock = stock - 1") // set stock = stock - 1
                .eq("voucher_id", voucherOrder.getVoucherId())// where id = ? and stock > 0
                .update();
        save(voucherOrder);
        return true;
    }


}
